using System;
using System.Threading;
using System.Threading.Tasks;
using Agriculture.Api.Read.Application.Command;
using Agriculture.Domain;
using Dapper;
using MediatR;
using Microsoft.Extensions.Configuration;
using MySql.Data.MySqlClient;

namespace Agriculture.Api.Read.Application.Handler
{
    /// <summary>
    /// 退款申请详情查询处理器
    /// </summary>
    public class RefundApplicationDetailQueryHandler : IRequestHandler<RefundApplicationDetailQuery, RefundApplicationDetailResult>
    {
        private readonly IConfiguration _configuration;

        public RefundApplicationDetailQueryHandler(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        public async Task<RefundApplicationDetailResult> Handle(RefundApplicationDetailQuery request, CancellationToken cancellationToken)
        {
            string connectionString = _configuration.GetConnectionString("DefaultConnection");

            using (var connection = new MySqlConnection(connectionString))
            {
                var sql = @"
                    SELECT r.* 
                    FROM refundapplicationmodel r
                    WHERE r.Id = @Id AND r.IsDeleted = 0";

                var refundApplication = await connection.QueryFirstOrDefaultAsync<dynamic>(sql, new { Id = request.Id });

                if (refundApplication == null)
                {
                    return null;
                }

                return new RefundApplicationDetailResult
                {
                    ServiceNo = refundApplication.ServiceNo,
                    Status = ConvertStatus(refundApplication.Status),
                    CreateTime = refundApplication.CreateTime != null ? refundApplication.CreateTime : DateTime.Now,
                    UserPhone = refundApplication.UserPhone,
                    OrderNo = refundApplication.OrderNo,
                    OrderAmount = refundApplication.Amount ?? 0, // 使用退款申请表中的金额字段
                    RefundAmount = refundApplication.RefundAmount,
                    RefundMethod = refundApplication.RefundMethod,
                    RefundType = refundApplication.RefundType,
                    Reason = refundApplication.Reason,
                    Processor = refundApplication.Processor,
                    ProcessTime = refundApplication.ProcessTime,
                    Remark = refundApplication.Remark
                };
            }
        }

        /// <summary>
        /// 转换状态码为状态文本
        /// </summary>
        private string ConvertStatus(int status)
        {
            switch (status)
            {
                case 0:
                    return "待处理";
                case 1:
                    return "已处理";
                case 2:
                    return "已拒绝";
                default:
                    return "未知";
            }
        }
    }
} 